<script setup>
import { ref, computed, reactive, watch } from "vue";
import { storeToRefs } from "pinia";
import { useRoute } from "vue-router";
import { useUserStore } from "@/stores/user";
import Zoom from './Zoom/Zoom.vue'
import { getGoodsDetailById } from '@/api/home.js'
import { insertCart } from '@/api/cart.js'
import { setDefaultAddr } from '@/api/user.js'
import { doAttributeList } from '@/comm/reg.js'
import { getCurrentInstance } from "vue";
import { useCartStore } from "@/stores/cart";
const internalInstance = getCurrentInstance();
const route = useRoute()


//获取商品详情
const goodDetail = ref(undefined)
const selSpecs = reactive({})
//根据规格计算对应价格
watch(selSpecs,(nv,ov) => {
   let flag = Object.values(nv).every(it => it)
   if(flag){
      const res = Object.values(nv).join(',')
      goodDetail.value.price = goodDetail.value.goodsSpecsList.find(it => it.goodsSpecsName === res).goodsPrice
   }
})
async function getGoodDetail() {
   const { data } = await getGoodsDetailById(route.params.id)
   data.goodsSpecsList = data.goodsSpecsList.filter(it => (it.goodsStock > 0)) //过滤掉没库存的
   goodDetail.value = data
   // 为数据添加specs字段
   const specs = doAttributeList(data.attributeList)
   specs.forEach(item => {
      selSpecs[item.key] = '' //初始化用户选择规格存储字段
   })
   specs.forEach(item => {
      item.value = item.value.map(it => {
         return { name: it, able: isAble(item.key, it, specs, data.goodsSpecsList) }
      })
   })
   goodDetail.value.specs = specs
   goodDetail.value.detail = goodDetail.value.detail.replace(/\{|\}|\"/g, '')
}
getGoodDetail()

// SKU逻辑
function isAble(key, value, specs, goodsSpecsList) {
   const copySelSpecs = JSON.parse(JSON.stringify(selSpecs))
   copySelSpecs[key] = value
   // var i = 0
   let flag = goodsSpecsList.some(it => {
      var i = 0
      for (let k in copySelSpecs) {
         if (copySelSpecs[k] !== '' && it.goodsSpecsName.includes(copySelSpecs[k])) {
            i++
         } else if (copySelSpecs[k] === '') {
            i++
         }
      }
      return i === specs.length
   })
   return flag
}
// 获取收货地址
const { addrList: addList } = storeToRefs(useUserStore())
const defaultAdd = computed(() => {
   return addList.value?.find(it => it.isDefault === 1)
})
// 更改地址地址
const dialogVisible = ref(false)
async function setAddr(obj) {
   await setDefaultAddr(obj.id)
   dialogVisible.value = false
   useUserStore().getAddrList()


}
// 选中sku
function changeSpec(key, value, able) {
   if (!able) return
   if (selSpecs[key] === value) {
      selSpecs[key] = ''
   } else {
      selSpecs[key] = value
   }
   goodDetail.value.specs.forEach(item => {
      item.value.forEach(it => {
         it.able = isAble(item.key, it.name, goodDetail.value.specs, goodDetail.value.goodsSpecsList)
      })
   })
}

// 加入购物车
// 加入购物车效果
let timer1 = undefined
function addCarAni(e) {
   let scoTop = document.documentElement.scrollTop
   let x = e.target.offsetLeft + 143
   let y = e.target.offsetTop + 7 - scoTop
   let cartPos = internalInstance.appContext.config.globalProperties.$cartPosition
   const dom = document.createElement('div')
   dom.style.position = 'fixed'
   dom.style.left = x + 'px'
   dom.style.top = y + 'px'
   dom.className = 'box'
   document.body.appendChild(dom)
   dom.style.transition = 'all 1s ease-in-out'
   dom.addEventListener('transitionend', function () {
      dom.style.transition = 'all 1s ease-in-out'
      cartPos.style.backgroundColor = "#fff"
      cartPos.style.color = '#5ebced'

      dom.style.opacity = 0
      if (timer1) {
         clearTimeout(timer1)
      }
      timer1 = setTimeout(() => {
         cartPos.style.backgroundColor = "#424242"
         cartPos.style.color = '#b0b0b0'
         clearTimeout(timer1)
         timer1 = undefined
      }, 1000)

      let timer = setTimeout(() => {
         this.remove()
         clearTimeout(timer)
      }, 1000)
   })
   console.log(dom.clientLeft);
   dom.style.top = 10 + 'px'
   dom.style.left = cartPos.offsetLeft + 25 + 'px'
}

let timer2 = undefined
function addCar(e) {

   if (timer2) {
      clearTimeout(timer2)
      timer2 = undefined
   }
   timer2 = setTimeout(async () => {
      const item = goodDetail.value.goodsSpecsList.find(it => {
         return it.goodsSpecsName === Object.values(selSpecs).join(',')
      })
      if (!item) {
         alert('请选择规格')
         return
      }
      const res = await insertCart({ goodsId: item.goodsId, goodsSpecsId: item.id })

      if (res.code === 0) {
         alert(res.msg)
         return
      } else {
         addCarAni(e)
      }
      useCartStore().getCartList()
   }, 500)
}



</script>

<template>
   <div class="detail">
      <div class="content">
         <div class="left">
            <Zoom :image="goodDetail?.image"></Zoom>
         </div>
         <div class="right">
            <h2>{{ goodDetail?.name }}</h2>
            <span style="color: #B0B0B0; ">{{ goodDetail?.description }}</span>
            <p>{{ goodDetail?.detail }}</p>
            <span class="price">￥{{ goodDetail?.price.toFixed(2) }}</span>
            <div class="address_book">
               <span></span>
               <span class="sp">{{ defaultAdd?.provinceName }}</span>
               <span class="sp">{{ defaultAdd?.cityName }}</span>
               <span class="sp">{{ defaultAdd?.districtName }}</span>
               <button @click="dialogVisible = true">修改</button>
            </div>
            <dl v-for="(item, index) in goodDetail?.specs" :key="index">
               <dt>{{ item.key }}</dt>
               <dd v-for="(it, index) in item.value" :key="index"
                  :class="[it.able ? '' : 'disable', selSpecs[item.key] === it.name ? 'active' : '']"
                  @click="changeSpec(item.key, it.name, it.able)">
                  {{ it.name }}
               </dd>
            </dl>
            <button class="shop_cart" @click="addCar">加入购物车</button>
         </div>
      </div>
      <!-- 弹框 -->
      <el-dialog v-model="dialogVisible" title="选择收货地址">
         <div class="address_book" v-for="item in addList" :key="item.id">
            <span class="sp"></span>
            <span class="sp">{{ item?.provinceName }}</span>
            <span class="sp">{{ item?.cityName }}</span>
            <span class="sp">{{ item?.districtName }}</span>
            <button @click="setAddr(item)">选择</button>
         </div>
      </el-dialog>
   </div>
</template>

<style scoped lang="less">
.detail {
   margin-bottom: 10px;

   .address_book {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 106px;
      border: 1px solid #e0e0e0;
      background-color: #fafafa;
      color: #5ebced;


      button {
         background-color: #fafafa;
         color: #5ebced;

      }

      .sp {
         margin: 0 10px !important;
      }

      :nth-child(1)::before {
         content: '\e662';
         font-family: 'iconfont';

      }
   }

   .content {
      overflow: hidden;

      .right {
         float: right;
         width: 600px;

         .shop_cart {
            margin-top: 20px;
            width: 299px;
            height: 56px;
            background-color: #5ebced;
            color: #fff;
         }

         p,
         span {
            color: #5ebced;
            margin: 10px 0;
         }

         .price {
            display: block;
            padding-bottom: 20px;
            width: 100%;
            border-bottom: 1px solid #e0e0e0;

         }

         dl {
            dt {
               height: 35px;
               line-height: 35px;
               font-size: 20px;
            }

            dd {
               display: inline-block;
               padding: 16px 120px;
               border: 1px solid #e0e0e0;
               margin-right: 5px;
               margin-bottom: 5px;
               cursor: pointer;
            }
         }
      }

      .left {
         float: left;
      }
   }

   .active {
      border-color: #5ebced !important;
   }

   .disable {
      color: #b8b7b7 !important;
   }
}
</style>
